package com.andooco.dataq.controller;

import com.andooco.dataq.common.Name2PasswordUtils;
import com.andooco.dataq.util.UserTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 用户登录
 *
 * @author andooco
 * 20201123
 */
@Slf4j
@Controller
public class IndexController {
    @RequestMapping({"/"})
    public String index() {
        return "login";
    }

    /**
     * 程序登录入口 andooco 20201123
     *
     * @param request
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model map) throws Exception {
        log.info("进入方法IndexController.login()");
        return "/login";
    }

    /**
     * 程序首页入口 andooco 20201123
     *
     * @param request
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping("/index")
    public String index(HttpServletRequest request, Model map) throws Exception {
        log.info("进入方法IndexController.index()");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        log.info("登录用户为：{}。登录密码为：{}", username, password);
        String msg = "";
        HttpSession session = request.getSession();
        if (Name2PasswordUtils.USER_NAME_TEST.equals(username)) {
            if (Name2PasswordUtils.USER_PASSWORD_TEST.equals(password)) {
                //登录后保存用户类型为测试人员
                session.setAttribute("userType", UserTypeEnum.TEST.getCode());
                session.setAttribute("username", username);
                map.addAttribute("userType", UserTypeEnum.TEST.getCode());
                return "index";
            } else {
                msg = Name2PasswordUtils.LOGIN_ERROR_MSG;
            }
        } else if (Name2PasswordUtils.USER_NAME_ROOT.equals(username)) {
            if (Name2PasswordUtils.USER_PASSWORD_ROOT.equals(password)) {
                //登录后保存用户类型为管理员
                session.setAttribute("userType", UserTypeEnum.ROOT.getCode());
                session.setAttribute("username", username);
                map.addAttribute("userType", UserTypeEnum.ROOT.getCode());
                return "index";
            } else {
                msg = Name2PasswordUtils.LOGIN_ERROR_MSG;
            }
        } else {
            msg = Name2PasswordUtils.LOGIN_ERROR_MSG;
        }
        map.addAttribute("msg", msg);
        // 此方法不处理登录成功,由shiro进行处理
        return "/login";
    }

    @RequestMapping("/403")
    public String unauthorizedRole() {
        System.out.println("------没有权限-------");
        return "403";
    }
}
